package com.xiaozhi.common.context;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

import com.xiaozhi.service.WxUserService;
import com.xiaozhi.service.impl.WxUserServerImpl;
import com.xiaozhi.vo.UserTokenVO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ServerWebExchange;

import java.text.SimpleDateFormat;
import java.util.Date;
//import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;

/**
 * @author weikaiyu
 * @version 1.0
 * @date 2022-04-02 17:44
 */
@Component
@Slf4j
public class UserTokenContextHolder {

    /**
     * 获取用户token
     *
     * @param token token
     * @return {@link UserTokenVO}
     */
    @SuppressWarnings("unchecked")
    public static UserTokenVO getUserTokenVOByToken(String token) {
        //RedisTemplate<String, Object> redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);

        //String tokenCacheKey = ConstantPool.getCacheTokenName() + StrUtil.COLON + token;
       // Object userTokenVOObj = redisTemplate.opsForValue().get(tokenCacheKey);

        //String userTokenStr = Optional.ofNullable(userTokenVOObj).map(Objects::toString)
        //        .orElseThrow(() -> new BasicInfoException(BasicInfoStatusEnum.TOKEN_AUTH.getCode(), BasicInfoStatusEnum.TOKEN_AUTH.getDesc()));

       // return JSONUtil.toBean(userTokenStr, UserTokenVO.class);
        //return wxUserService.getUserFromToken(token);
        //wxUserService userSerivce = new WxUserServerImpl();
        
       return null;
    }

    /**
     * 获取用户token ，从request Authorization中获取
     *
     * @return
     */
    public static UserTokenVO getUserTokenVOByToken() {
        String token = getCurrentUserTokenReal().toString();
        return getUserTokenVOByToken(token);
    }

    /**
     * 获取userId
     *
     * @param token
     * @return userId
     */
    public static Integer getUserId(String token) {
        return getUserTokenVOByToken(token).getUserId();
    }

    /**
     * 获取openid
     *
     * @param token
     * @return openid
     */
    public static String getOpenid(String token) {
        return getUserTokenVOByToken(token).getOpenId();
    }


    /**
     * 获取当前请求下 请求头中的 Authorization 或者 请求参数中 token值
     *
     * @return
     */
   /*  public static String getCurrentUserTokenReal() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token;
        if (request != null) {
            String authToken = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(authToken)) {
                return authToken;
            }
            token = request.getParameter("token");
            if (!StringUtils.isEmpty(token)) {
                return token;
            }
        }
        return null;
    }*/
    public static Mono<String> getCurrentUserTokenReal() {
        return Mono.deferContextual(ctx -> {
            // 从 Reactor 上下文获取 ServerWebExchange
            ServerWebExchange exchange = ctx.get(ServerWebExchange.class);
            ServerHttpRequest request = exchange.getRequest();
            
            // 先检查 Authorization 头
            String authHeader = request.getHeaders().getFirst("Authorization");
            if (authHeader != null && !authHeader.isEmpty()) {
                return Mono.just(authHeader);
            }
            
            // 再检查 URL 参数
            String tokenParam = request.getQueryParams().getFirst("token");
            if (tokenParam != null && !tokenParam.isEmpty()) {
                return Mono.just(tokenParam);
            }
            
            // 都没有则返回空
            return Mono.empty();
        });
    }
    public static String GetUserTokenFromWebExchange(ServerWebExchange exchange){
         ServerHttpRequest request = exchange.getRequest();
            
            // 先检查 Authorization 头
            String authHeader = request.getHeaders().getFirst("Authorization");
            if (authHeader != null && !authHeader.isEmpty()) {
                return authHeader;
            }
            
            // 再检查 URL 参数
            String tokenParam = request.getQueryParams().getFirst("token");
            if (tokenParam != null && !tokenParam.isEmpty()) {
                return tokenParam;
            }
        return null;
    }
    public static String   generateOrderNo() {
        // 时间戳格式：yyyyMMddHHmmssSSS
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        
        // 随机数（6位数字）
        Random random = new Random();
        int randomNum = random.nextInt(900000) + 100000;
        
        // 组合：时间戳+随机数
        return "PAY" + timestamp + randomNum;
    }
}
